package com.live.task;

import java.io.InputStream;
import java.net.URI;
import java.util.HashMap;
import java.util.Map;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.TextView;

import com.live.activity.R;
import com.live.common.Constant;
import com.live.tools.LiveTools;

public class LiveMsgCount extends AsyncTask<Bundle, Integer, String> {

	private Map<String, Object> Obj;

	private String uId = null;

	private String userId = null;

	private View view;

	private Context context;

	public LiveMsgCount(Context context, View view) {
		this.context = context;
		this.view = view;
	}

	// 此方法在主线程执行,当任务执行之前开始调用此方法，可以在这里显示进度对话框
	@Override
	protected void onPreExecute() {
		super.onPreExecute();
		Log.i("PageTask", "onPreExecute()  " + Thread.currentThread().getId());
	}

	// 此方法在后台线程执行，完成任务的主要工作，通常需要较长的时间。
	// 在执行过程中可以调用publicProgress(Progress...)来更新任务的进度。

	@Override
	protected String doInBackground(Bundle... params) {
		Log.i("PageTask", "doInBackground... " + Thread.currentThread().getId());

		userId = params[0].getString("userId");
		uId = params[0].getString("uId");

		String url = Constant.SITE_URL + "live_message_count.php?locale=" + LiveTools.getLocaleLanguage();
		url += "&uId=" + uId + "&userId=" + userId;

		Obj = getMsgCount(url);

		publishProgress();
		return null;
	}

	// 此方法在主线程执行，用于显示任务执行的进度
	@Override
	protected void onProgressUpdate(Integer... values) {
		super.onProgressUpdate(values);
		Log.i("PageTask", "onProgressUpdate()  " + Thread.currentThread().getId());

		if (!Obj.isEmpty()) {
			TextView userReplayText = (TextView) view.findViewById(R.id.userReplayText);
			String rCount = context.getString(R.string.user_replay_count);
			if (Integer.valueOf((String) Obj.get("rCount")) > 0) {
				userReplayText.setText(rCount.replace(Constant.NUM_ZERO, (String) Obj.get("rCount")));
				userReplayText.setTextColor(Color.RED);
			} else {
				userReplayText.setText(R.string.user_replay_count);
				userReplayText.setTextColor(Color.parseColor("#9CCEE7"));
			}
			TextView userMsgText = (TextView) view.findViewById(R.id.userMsgText);
			String mCount = context.getString(R.string.user_msg_count);
			if (Integer.valueOf((String) Obj.get("mCount")) > 0) {
				userMsgText.setText(mCount.replace(Constant.NUM_ZERO, (String) Obj.get("mCount")));
				userMsgText.setTextColor(Color.RED);
			} else {
				userMsgText.setText(R.string.user_msg_count);
				userMsgText.setTextColor(Color.parseColor("#9CCEE7"));
			}
			TextView userFriendText = (TextView) view.findViewById(R.id.userFriendText);
			String fCount = context.getString(R.string.user_friend_count);
			if (Integer.valueOf((String) Obj.get("fCount")) > 0) {
				userFriendText.setText(fCount.replace(Constant.NUM_ZERO, (String) Obj.get("fCount")));
				userFriendText.setTextColor(Color.RED);
			} else {
				userFriendText.setText(R.string.user_friend_count);
				userFriendText.setTextColor(Color.parseColor("#9CCEE7"));
			}
		}
	}

	// 此方法在主线程执行，任务执行的结果作为此方法的参数返回。
	@Override
	protected void onPostExecute(String result) {
		Log.i("PageTask", "onPostExecute()  " + Thread.currentThread().getId());
	}

	/**
	 * 记录观看比赛详细页的信息
	 * 
	 * @param url
	 * @return
	 */
	private Map<String, Object> getMsgCount(String url) {
		Map<String, Object> data = new HashMap<String, Object>();
		HttpClient client = new DefaultHttpClient();
		try {
			HttpGet request = new HttpGet(new URI(url));
			request.addHeader("Accept-Encoding", "gzip");
			HttpResponse response = client.execute(request);

			if (response.getStatusLine().getStatusCode() == 200) {
				HttpEntity entity = response.getEntity();

				if (entity != null) {
					String out = null;
					InputStream is = entity.getContent();
					if (entity.getContentEncoding().getValue().contains("gzip")) {
						out = LiveTools.isToString(is);
					} else {
						out = EntityUtils.toString(entity);
					}
					try {
						JSONArray json = new JSONObject(out).getJSONArray("results");
						data.put("rCount", json.getJSONObject(0).get("c"));
						data.put("mCount", json.getJSONObject(1).get("c"));
						data.put("fCount", json.getJSONObject(2).get("c"));
					} catch (JSONException e) {
						e.printStackTrace();
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return data;
	}

}